package cn.yujiago.springboot.service.impl;

import cn.yujiago.springboot.mapper.FileMapper;
import cn.yujiago.springboot.entity.File;
import cn.yujiago.springboot.pojo.FileResult;
import cn.yujiago.springboot.pojo.LayuiTableResult;
import cn.yujiago.springboot.service.FileService;
import cn.yujiago.springboot.utils.MyStringUtils;
import cn.yujiago.springboot.utils.QiniuCloudUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;
import java.util.UUID;

@CacheConfig(cacheNames = "file", cacheManager = "redisCacheManager")
@Service
public class FileServiceImpl implements FileService {

    @Resource
    private FileMapper fileMapper;
    @Resource
    private PageHelper pageHelper;

    @Override
    @Transactional
    @CacheEvict(allEntries = true)
    public FileResult uploadFileToQiniuAndInsert(MultipartFile file) {

        // 判断文件是否为空
        if(file.isEmpty()) {
            return FileResult.builder().code(404).msg("文件为空！").build();
        }

        try {
            byte[] bytes = file.getBytes();
            // 获取文件扩展名
            String suffix = MyStringUtils.getFileSuffix(file.getOriginalFilename());
            String fileName = UUID.randomUUID().toString() + suffix;
            //使用base64方式上传到七牛云
            String url = QiniuCloudUtil.put64file(bytes, fileName);

            File newFile = File.builder()
                                .id(MyStringUtils.getUUID())
                                .fileName(file.getOriginalFilename())
                                .size(file.getSize() / 1024)
                                .url(url)
                                .uploadTime(new Timestamp(System.currentTimeMillis()))
                                .status(0).build();

            // 插入数据库
            fileMapper.insertFile(newFile);

            return FileResult.builder().code(200).msg("文件上传成功！").build();

        } catch (Exception e) {
            return FileResult.builder().code(500).msg("文件上传发生异常！").build();
        }
    }

    @Override
    @Cacheable(key = "'getFileByCondition'+#page+#rows+#fileName", unless = "#result.code!=0")
    public LayuiTableResult<File> getFileByCondition(Integer page, Integer rows, String fileName) {
        // 1、设置分页信息，包括当前页数和每页显示的总计数
        pageHelper.startPage(page, rows);
        // 2、执行查询
        List<File> files = null;
        if(StringUtils.isBlank(fileName)){
            files = fileMapper.selectAllFile();
        }else{
            files = fileMapper.selectFileByName(fileName);
        }
        // 3、获取分页查询后的数据
        PageInfo<File> pageInfo = new PageInfo<>(files);
        // 4、创建返回结果对象
        LayuiTableResult<File> result = new LayuiTableResult<>();
        if(files != null){
            result.setCode(0);
            result.setMsg("查询成功！");
            // 设置获取到的总记录数total
            result.setCount(pageInfo.getTotal());
            result.setData(files);
            return result;
        }else{
            result.setCode(1);
            result.setMsg("查询失败！");
            return result;
        }
    }
}
